package com.boot.security.server.utils;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;

import java.awt.Color;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * ss
 * @author king
 */
public class ExcelUtils {
    /**
     * 2003- 版本的excel
     */
    private final static String EXCEL_2003_L = ".xls";
    /**
     * 2007+ 版本的excel
     */
    private final static String EXCEL_2007_U = ".xlsx";
    private final static String XLS = "xls";
    private final static String XLSX = "xlsx";
    private final static String GENERAL = "General";
    private final static String M_D_YY = "m/d/yy";

    /**
     * Excel导入
     */
    public static List<List<Object>> getDataListByExcel (InputStream in, String fileName) throws Exception {
        List<List<Object>> list;
        //创建Excel工作薄
        Workbook work = getWorkbook(in, fileName);
        Sheet sheet;
        Row row;
        Cell cell;
        list = new ArrayList<>();
        //遍历Excel中所有的sheet
        for (int i = 0; i < work.getNumberOfSheets(); i++) {
            sheet = work.getSheetAt(i);
            if (sheet == null) {
                continue;
            }
            //遍历当前sheet中的所有行
            //包涵头部，所以要小于等于最后一列数,这里也可以在初始值加上头部行数，以便跳过头部
            for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {
                //读取一行
                row = sheet.getRow(j);
                //去掉空行和表头
                if (row == null || row.getFirstCellNum() == j) {
                    continue;
                }
                //遍历所有的列
                List<Object> li = new ArrayList<>();
                for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
                    cell = row.getCell(y);

                    li.add(getCellValue(cell));
                }
                // 表头列与内容列不匹配时填充
                if (row.getLastCellNum() < sheet.getRow(0).getLastCellNum()) {
                    // 填充
                    for (int x = row.getLastCellNum(); x < sheet.getRow(0).getLastCellNum(); x++) {
                        li.add("");
                    }
                } else if (row.getLastCellNum() > sheet.getRow(0).getLastCellNum()) {
                    // 删除多余列
                    if (row.getLastCellNum() > sheet.getRow(0).getLastCellNum()) {
                        li.subList(sheet.getRow(0).getLastCellNum(), row.getLastCellNum()).clear();
                    }
                }
                list.add(li);
            }
        }
        return list;
    }

    public static List<List<String>> readExcel (String path) {
        String fileType = path.substring(path.lastIndexOf(".") + 1);
        // return a list contains many list
        List<List<String>> lists = new ArrayList<>();
        //读取excel文件
        InputStream is = null;
        try {
            is = new FileInputStream(path);
            //获取工作薄
            Workbook wb;
            if (fileType.equals(XLS)) {
                wb = new HSSFWorkbook(is);
            } else if (fileType.equals(XLSX)) {
                wb = new XSSFWorkbook(is);
            } else {
                return null;
            }

            //读取第一个工作页sheet
            Sheet sheet = wb.getSheetAt(0);
            //第一行为标题
            for (Row row : sheet) {
                ArrayList<String> list = new ArrayList<>();
                for (Cell cell : row) {
                    //根据不同类型转化成字符串
                    cell.setCellType(Cell.CELL_TYPE_STRING);
                    list.add(cell.getStringCellValue());
                }
                lists.add(list);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return lists;
    }

    /**
     * 描述：根据文件后缀，自适应上传文件的版本
     */
    public static Workbook getWorkbook (InputStream inStr, String fileName) throws Exception {
        Workbook wb;
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        if (EXCEL_2003_L.equals(fileType)) {
            //2003-
            wb = new HSSFWorkbook(inStr);
        } else if (EXCEL_2007_U.equals(fileType)) {
            //2007+
            wb = new XSSFWorkbook(inStr);
        } else {
            throw new Exception("解析的文件格式有误！");
        }
        return wb;
    }

    /**
     * 描述：对表格中数值进行格式化
     */
    public static Object getCellValue (Cell cell) {
        if (cell == null) {
            return "";
        }
        Object value;
        //格式化字符类型的数字
        DecimalFormat df = new DecimalFormat("0");
        //日期格式化
        SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd");
        //格式化数字
        DecimalFormat df2 = new DecimalFormat("0.00");
        switch (cell.getCellType()) {
            case Cell.CELL_TYPE_STRING:
                value = cell.getRichStringCellValue().getString();
                break;
            case Cell.CELL_TYPE_NUMERIC:
                if (GENERAL.equals(cell.getCellStyle().getDataFormatString())) {
                    value = df.format(cell.getNumericCellValue());
                } else if (M_D_YY.equals(cell.getCellStyle().getDataFormatString())) {
                    value = sdf.format(cell.getDateCellValue());
                } else {
                    value = df2.format(cell.getNumericCellValue());
                }
                break;
            case Cell.CELL_TYPE_BOOLEAN:
                value = cell.getBooleanCellValue();
                break;
            case Cell.CELL_TYPE_BLANK:
                value = "";
                break;
            default:
                value = cell.getStringCellValue();
                break;
        }
        return value;
    }

    /**
     * 导入Excel表结束
     * 导出Excel表开始
     * @param sheetName 工作簿名称
     * @param clazz     数据源model类型
     * @param objs      excel标题列以及对应model字段名
     * @param map       标题列行数以及cell字体样式
     */
    public static XSSFWorkbook createExcelFile (Class clazz, List objs, Map<Integer, List<ExcelBean>> map, String sheetName) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, ClassNotFoundException, IntrospectionException, ParseException {
        // 创建新的Excel工作簿
        XSSFWorkbook workbook = new XSSFWorkbook();
        // 在Excel工作簿中建一工作表，其名为缺省值, 也可以指定Sheet名称
        XSSFSheet sheet = workbook.createSheet(sheetName);
        // 以下为excel的字体样式以及excel的标题与内容的创建，下面会具体分析;
        //字体样式
        createFont(workbook);
        //创建标题（头）
        createTableHeader(sheet, map);
        //创建内容
        createTableRows(sheet, map, objs, clazz);
        return workbook;
    }

    private static XSSFCellStyle fontStyle;
    private static XSSFCellStyle fontStyle2;

    public static void createFont (XSSFWorkbook workbook) {
        // 表头
        fontStyle = workbook.createCellStyle();
        XSSFFont font1 = workbook.createFont();

        // 粗体显示
        font1.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
        // 设置字体类型
        font1.setFontName("黑体");
        // 设置字体大小
        font1.setFontHeightInPoints((short) 14);
        fontStyle.setFont(font1);
        // 下边框
        fontStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);
        // 左边框
        fontStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);
        // 上边框
        fontStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);
        // 右边框
        fontStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
        // 居中
        fontStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
        // 垂直
        fontStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
        // 设置填充方案
        fontStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        // 设置填充颜色
        fontStyle.setFillForegroundColor(new XSSFColor(new Color(172, 186, 202)));

        // 内容
        fontStyle2 = workbook.createCellStyle();
        XSSFFont font2 = workbook.createFont();
        // 设置字体类型
        font2.setFontName("黑体");
        // 设置字体大小
        font2.setFontHeightInPoints((short) 14);
        // 设置自动换行
        fontStyle2.setFont(font2);
        fontStyle2.setWrapText(true);
        // 下边框
        fontStyle2.setBorderBottom(XSSFCellStyle.BORDER_THIN);
        // 左边框
        fontStyle2.setBorderLeft(XSSFCellStyle.BORDER_THIN);
        // 上边框
        fontStyle2.setBorderTop(XSSFCellStyle.BORDER_THIN);
        // 右边框
        fontStyle2.setBorderRight(XSSFCellStyle.BORDER_THIN);
        // 居中
        fontStyle2.setAlignment(XSSFCellStyle.ALIGN_CENTER);
        // 垂直
        fontStyle2.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
    }

    /**
     * 根据ExcelMapping 生成列头（多行列头）
     * @param sheet 工作簿
     * @param map   每行每个单元格对应的列头信息
     */
    public static void createTableHeader (XSSFSheet sheet, Map<Integer, List<ExcelBean>> map) {
        //cell起始位置
        int startIndex = 0;
        //cell终止位置
        int endIndex = 0;
        for (Map.Entry<Integer, List<ExcelBean>> entry : map.entrySet()) {
            XSSFRow row = sheet.createRow(entry.getKey());
            List<ExcelBean> excels = entry.getValue();
            for (int x = 0; x < excels.size(); x++) {
                //合并单元格
                if (excels.get(x).getCols() > 1) {
                    if (x == 0) {
                        endIndex += excels.get(x).getCols() - 1;
                        CellRangeAddress range = new CellRangeAddress(0, 0, startIndex, endIndex);
                        sheet.addMergedRegion(range);
                    } else {
                        endIndex += excels.get(x).getCols();
                        CellRangeAddress range = new CellRangeAddress(0, 0, startIndex, endIndex);
                        sheet.addMergedRegion(range);
                    }
                    startIndex += excels.get(x).getCols();
                    XSSFCell cell = row.createCell(startIndex - excels.get(x).getCols());
                    // 设置内容
                    cell.setCellValue(excels.get(x).getHeadTextName());
                    if (excels.get(x).getCellStyle() != null) {
                        // 设置格式
                        cell.setCellStyle(excels.get(x).getCellStyle());
                    }
                    cell.setCellStyle(fontStyle);
                } else {
                    XSSFCell cell = row.createCell(x);
                    // 设置内容
                    cell.setCellValue(excels.get(x).getHeadTextName());
                    if (excels.get(x).getCellStyle() != null) {
                        // 设置格式
                        cell.setCellStyle(excels.get(x).getCellStyle());
                    }
                    cell.setCellStyle(fontStyle);
                }
            }
        }
    }

    public static void createTableRows (XSSFSheet sheet, Map<Integer, List<ExcelBean>> map, List objs, Class clazz) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, IntrospectionException, ClassNotFoundException, ParseException {
        int rowindex = map.size();
        int maxKey = 0;
        List<ExcelBean> ems;
        for (Map.Entry<Integer, List<ExcelBean>> entry : map.entrySet()) {
            if (entry.getKey() > maxKey) {
                maxKey = entry.getKey();
            }
        }
        ems = map.get(maxKey);
        for (Object obj : objs) {
            XSSFRow row = sheet.createRow(rowindex);
            // 行高
            // row.setHeight((short) (10 * 20));
            for (int i = 0; i < ems.size(); i++) {
                ExcelBean em = ems.get(i);
                // 获得get方法
                PropertyDescriptor pd = new PropertyDescriptor(em.getPropertyName(), clazz);
                Method getMethod = pd.getReadMethod();
                Object rtn = getMethod.invoke(obj);
                String value = "";
                // 如果是日期类型进行转换
                if (rtn != null) {
                    if (rtn instanceof Date) {
                        value = DateUtils.formatToyyyyMMddHHmmss((Date) rtn);
                    } else if (rtn instanceof BigDecimal) {
                        NumberFormat nf = new DecimalFormat("#,##0.00");
                        value = nf.format(rtn);
                    } else if ((rtn instanceof Integer) && (Integer.parseInt(rtn.toString()) < 0)) {
                        value = rtn.toString();
                    } else {
                        value = rtn.toString();
                    }
                }
                XSSFCell cell = row.createCell(i);
                cell.setCellValue(value);
                cell.setCellType(XSSFCell.CELL_TYPE_STRING);
                cell.setCellStyle(fontStyle2);
            }
            rowindex++;
        }
        // 设置列宽
        sheet.setColumnWidth(0, 30 * 256);
        sheet.setColumnWidth(1, 12 * 256);
        sheet.setColumnWidth(2, 20 * 256);
        sheet.setColumnWidth(3, 40 * 256);
        sheet.setColumnWidth(4, 47 * 256);
        sheet.setColumnWidth(5, 15 * 256);
    }
}
